package com.wyz.web;

import com.wyz.entity.UserInfo;
import com.wyz.service.StudentService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;
@MultipartConfig
@WebServlet("/updateUser2")
public class UpdateUserServlet2 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        //获取文件域对象
        Part part = req.getPart("newPic");
        //获取上传文件名
        String fileName = part.getSubmittedFileName();
        String path="d:/pic";
        //获取表单数据-->存到map中
        Map<String, String[]> map = req.getParameterMap();
        UserInfo ui = new UserInfo();
        //调用BeanUtils中映射方法将map中的数据映射到对象中
        try {
            BeanUtils.populate(ui,map);
            if(!"".equals(fileName)){
                //图片修改-->将新上传的图片名更新到s对象的spic的属性-->更新-->删除原来图片
                fileName= UUID.randomUUID()+fileName;
                ui.setSpic(fileName);
                part.write(path+ File.separator+fileName);
                //删除老图片
                File f = new File(path+File.separator+map.get("spic")[0]);
                f.delete();
            }
            //更新操作
            StudentService ss = new StudentService();
            boolean flag = ss.updateUser(ui);
            if(flag){
                //修改成功
                req.getRequestDispatcher("studentAll").forward(req,resp);
            }else{
                //修改失败
                pw.println("修改学生信息错误");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
